package com.liu.lab05.servlet;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//------------------------------------
		// 设置访问次数的代码
		// 获取 ServletContext
		ServletContext context = getServletContext();

		// 获取当前的访问计数
		Integer visitCount = (Integer) context.getAttribute("PAGE_VISIT_COUNT");

		// 增加访问计数
		if (visitCount == null) {
			visitCount = 0;
		}
		visitCount++;
		// 输出访问次数
		// 更新访问计数
		context.setAttribute("PAGE_VISIT_COUNT", visitCount);




		//-----------------------------------------
		String account = request.getParameter("account");
		String password = request.getParameter("password");

		String role=request.getParameter("role");
		HttpSession session = request.getSession();
		session.setAttribute( "user", account);
		session.setAttribute("password", password);
		RequestDispatcher rd=null;
		if(account!=null && role.equals("admin")){
			// 管理员用户
			//对于成功登录的用户需要在session保存登录名信息( "user", account );
			session.setAttribute( "user", account );
			session.setAttribute("password", password);
			rd=request.getRequestDispatcher("/admin/admin.jsp");
			rd.forward(request, response);
		}else if (account!=null && role.equals("common")){
			///  这里是普通用户
			session.setAttribute( "user", account );
			session.setAttribute("password", password);
			rd=request.getRequestDispatcher("/common/common.jsp");
			rd.forward(request, response);
		}else{
			response.sendRedirect("login.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
